package com.softstao.guoyu.mvp.api;

import android.os.Environment;
import android.util.Log;

import com.google.gson.Gson;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.softstao.guoyu.global.GsonManager;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.ResponseEntity;
import com.softstao.guoyu.mvp.events.ActionEvent;
import com.softstao.guoyu.mvp.events.NetWorkEvent;
import com.softstao.guoyu.mvp.rxbus.RxBus;
import com.softstao.guoyu.utils.MyHttpParams;
import com.softstao.softstaolibrary.library.wechatpay.MD5Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.util.Map;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by xuhon on 2016/4/22.
 */
public class VolleyApi {
    private String url;
    private CustomRxVolley.Builder rxVolleyBuilder;
    private Gson gson = GsonManager.getInstance().getGson();
    private Type type;
    private Subscription subscription;
    private Action1<Object> action1;
    private boolean isList = false;
    private File f= new File(Environment.getExternalStorageDirectory()+"/guoyu/");
    private HttpCallback callback;
    //    private Map<String,String> header;
    private SharePreferenceManager manager = SharePreferenceManager.getInstance();
    public VolleyApi(){
//        RxVolley.setRequestQueue(RequestQueue.newRequestQueue(f));
        rxVolleyBuilder=new CustomRxVolley.Builder();
        callback = new HttpCallback() {
            @Override
            public void onSuccess(Map<String, String> headers, byte[] t) {
                super.onSuccess(headers, t);
                if(headers.get("Set-Cookie")!=null){
                    manager.setCookie(headers.get("Set-Cookie").substring(0, headers.get("Set-Cookie").indexOf(";")));
                }
                ResponseEntity responseEntity = new ResponseEntity();
                if(url.contains("wx_interface")){
                    action1.call(new String(t));
                }else{
                    String json = new String(t);
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        responseEntity.fromJson(jsonObject);
                        dealNetWork(responseEntity);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        RxBus.get().post(ActionEvent.ERROR,"JSON数据格式错误");
                    }
                }
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                NetWorkEvent netWorkEvent = new NetWorkEvent();
                netWorkEvent.setErrorNo(errorNo);
                netWorkEvent.setStrMsg(strMsg);
                RxBus.get().post(netWorkEvent);
                if (isList){
                    RxBus.get().post(ActionEvent.REFRESH_OR_LOAD_FINISH,ActionEvent.REFRESH_OR_LOAD_FINISH);
                }
                Log.e("error",errorNo+"");
            }
        };
    }

    public VolleyApi(String url , Type type) {
        this();
        this.url = url;
        this.type =  type;
    }

    /**
     * 获取列表数据
     *
     * @param page 　页码
     */
    public void get(int page) {
        int offset = page * 10;
        MyHttpParams params = new MyHttpParams("pageSize","10","pageIndex",offset);
        get(url, params);
    }

    public void get(MyHttpParams params, int page) {
        int offset = page * 10;
        params.put("pageSize", "10");
        params.put("pageIndex", offset + "");
        this.get(url, params);
    }

    public void get() {
        this.get(url, null);
    }

    public void get(MyHttpParams params) {
        this. get(this.url, params);
    }

    public void get(String url, MyHttpParams params) {
        if(manager.getCookie()!=null){
            if(params==null){
                params = new MyHttpParams();
            }
            params.putHeaders("Cookie",manager.getCookie());
        }
//        if(UserManager.getInstance().getUser()!=null){
//            if(UserManager.getInstance().getUser().getSign()!=null){
//                url=url.concat("&sign="+UserManager.getInstance().getUser().getSign());
//            }
//        }
        params.put("apptype","android");
        params.put("timestamp", String.valueOf(System.currentTimeMillis()/1000));
        String sign = MD5Util.MD5Encode((params.getUrlParams().toString().replaceAll("\\?","").replaceAll("&","").replaceAll("=","")+"42b33856fe11773dce71bb727cead637").toLowerCase(),null);
        params.put("sign",sign);
        rxVolleyBuilder.url(url).httpMethod(RxVolley.Method.GET)
                .params(params)
                .contentType(RxVolley.ContentType.FORM)
                .shouldCache(true)
                .callback(callback).doTask();
//        return rxVolleyBuilder.url(url)
//                .httpMethod(RxVolley.Method.GET)
//                .cacheTime(1)
//                .params(params)
//                .contentType(RxVolley.ContentType.FORM)
//                .shouldCache(true)
//                .callback(callback)//网络错误回调
//                .getResult()
//                .filter(this::isSuccess)
//                .map(this::returnObject)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread());
    }

    public void post(MyHttpParams params) {
        this.post(this.url, params);
    }

    public void post(String url,MyHttpParams params) {
        if(manager.getCookie()!=null){
            params.putHeaders("Cookie",manager.getCookie());
        }
//        if(UserManager.getInstance().getUser()!=null){
//            if(UserManager.getInstance().getUser().getSign()!=null){
//                url=url.concat("&sign="+UserManager.getInstance().getUser().getSign());
//            }
//        }
        params.put("apptype","android");
        params.put("timestamp", String.valueOf(System.currentTimeMillis()/1000));
        String sign = MD5Util.MD5Encode((params.getUrlParams().toString().replaceAll("\\?","").replaceAll("&","").replaceAll("=","")+"42b33856fe11773dce71bb727cead637").toLowerCase(),null);
        params.put("sign",sign);
        rxVolleyBuilder
                .httpMethod(RxVolley.Method.POST)
                .params(params)
                .url(url)
                .contentType(RxVolley.ContentType.FORM)
                .timeout(5000)
                .callback(callback).doTask();

//        return rxVolleyBuilder.url(url)
//                .httpMethod(RxVolley.Method.POST)
//                .params(params)
//                .contentType(RxVolley.ContentType.FORM)
//                .shouldCache(false)
//                .callback(callback)//网络错误回调
//                .getResult()
//                .filter(this::isSuccess)
//                .map(this::returnObject)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread());
    }


    public void dealNetWork(ResponseEntity responseEntity){
        int error = responseEntity.getErrCode();
        ResponseEntity.ERROR code = ResponseEntity.ERROR.integerToEnum(error);
        switch (code){
            case SUCCESS:
                subscription = Observable
                        .just(type!=null?gson.fromJson(responseEntity.getData().toString(),type):responseEntity.getData())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(action1, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                RxBus.get().post(ActionEvent.ERROR,"格式错误");
                            }
                        }, new Action0() {
                            @Override
                            public void call() {
                                onComplete();
                            }
                        });
                break;
            case FAILED:
                RxBus.get().post(ActionEvent.ERROR,responseEntity.getErrMsg());
                break;
        }
        if (isList){
            RxBus.get().post(ActionEvent.REFRESH_OR_LOAD_FINISH,ActionEvent.REFRESH_OR_LOAD_FINISH);
        }
//        NotifyEvent notifyEvent = new NotifyEvent();
//        notifyEvent.setNotify(responseEntity.getNotify());
//        notifyEvent.setNotify_focus(responseEntity.getNotify_focus());
//        notifyEvent.setCart_notify(responseEntity.getCart_notify());
//        RxBus.get().post(notifyEvent);
    }
    public void onComplete(){
        if(!subscription.isUnsubscribed()&& null !=subscription){
            subscription.unsubscribe();
        }
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public Action1<Object> getAction1() {
        return action1;
    }

    public void setAction1(Action1<Object> action1) {
        this.action1 = action1;
    }

    public boolean isList() {
        return isList;
    }

    public void setList(boolean list) {
        isList = list;
    }
}